<script setup>
import { ref } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { userAddService, userEditService } from '@/api/user'
// 控制抽屉显示隐藏
const visibleDrawer = ref(false)
//默认数据
const defaultForm = {
  id: '',
  studentName: '',
  studentSex: '',
  studentId: '',
  studentTel: '',
  studentGrade: '',
  studentClass: '',
  studentInstruction: '',
  studentDormitory: '',
  politicalStatus: '',
  department: '',
  holdPostion: '',
  studentCounsellor: '',
  counsellorTel: '',
  studentGpa: '',
  professionalRanking: '',
  classRanking: ''
}
// 准备数据
const studentForm = ref({ ...defaultForm })

// 提交
const emit = defineEmits(['success'])
const onPublish = async () => {
  // 发请求
  if (studentForm.value.id) {
    // 编辑操作
    console.log(studentForm.value)
    await userEditService(studentForm.value)
    ElMessage.success('修改成功')
    visibleDrawer.value = false
    emit('success', 'edit')
  } else {
    // 添加操作
    // console.log(studentForm)
    await userAddService(studentForm.value)
    ElMessage.success('添加成功')
    visibleDrawer.value = false
    // 通知到父组件，添加成功了
    emit('success', 'add')
  }
}

// 组件对外暴露一个方法 open，基于open传来的参数，区分添加还是编辑
// open({})  => 表单无需渲染，说明是添加
// open({ id, ..., ... })  => 表单需要渲染，说明是编辑
// open调用后，可以打开抽屉
const editorRef = ref()
const open = async (row) => {
  visibleDrawer.value = true // 显示抽屉

  if (row.id) {
    // 需要基于 row.id 发送请求，获取编辑对应的详情数据，进行回显
    studentForm.value = { ...row }
  } else {
    studentForm.value = { ...defaultForm } // 基于默认的数据，重置form数据
    // 这里重置了表单的数据，但是图片上传img地址，富文本编辑器内容 => 需要手动重置
    editorRef.value.setHTML('')
  }
}
// 添加监听学号字段输入事件的处理程序
const handleStudentIdInput = (value) => {
  if (value && value.length >= 4 && /^\d+$/.test(value)) {
    studentForm.value.studentGrade = value.substring(0, 4) + '年级'
  } else {
    studentForm.value.studentGrade = ''
  }
}

defineExpose({
  open
})

const rules = {
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^[0-9]{16}$/, message: '学号必须为16位的数字', trigger: 'blur' }
  ],
  studentName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  studentTel: [
    {
      pattern: /^[0-9]{11}$/,
      message: '请输入11位数字电话号码',
      trigger: 'blur'
    }
  ],
  counsellorTel: [
    {
      pattern: /^[0-9]{11}$/,
      message: '请输入11位数字电话号码',
      trigger: 'blur'
    }
  ],
  professionalRanking: [
    { pattern: /^\d+$/, message: '专业排名必须为数字', trigger: 'blur' }
  ],
  classRanking: [
    { pattern: /^\d+$/, message: '班级排名必须为数字', trigger: 'blur' }
  ]
}
</script>

<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="studentForm.id ? '编辑学生' : '添加学生'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="studentForm" label-width="100px" :rules="rules">
      <el-form-item label="学号" prop="studentId">
        <el-input
          v-model="studentForm.studentId"
          placeholder="请输入学号"
          @input="handleStudentIdInput($event)"
        ></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="studentName">
        <el-input
          v-model="studentForm.studentName"
          placeholder="请输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="studentForm.studentSex" style="width: 650px">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="年级">
        <el-input v-model="studentForm.studentGrade" readonly></el-input>
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="studentForm.studentClass"></el-input>
      </el-form-item>
      <el-form-item label="所在部门">
        <el-input v-model="studentForm.department"></el-input>
      </el-form-item>
      <el-form-item label="双创职位">
        <el-input v-model="studentForm.holdPostion"></el-input>
      </el-form-item>
      <el-form-item label="政治面貌">
        <el-select v-model="studentForm.politicalStatus" style="width: 650px">
          <el-option label="党员" value="党员" />
          <el-option label="团员" value="团员" />
          <el-option label="群众" value="群众" />
        </el-select>
      </el-form-item>
      <el-form-item label="电话" prop="studentTel">
        <el-input v-model="studentForm.studentTel"></el-input>
      </el-form-item>
      <el-form-item label="绩点">
        <el-input v-model="studentForm.studentGpa"></el-input>
      </el-form-item>
      <el-form-item label="专业排名" prop="professionalRanking">
        <el-input v-model="studentForm.professionalRanking"></el-input>
      </el-form-item>
      <el-form-item label="班级排名" prop="classRanking">
        <el-input v-model="studentForm.classRanking"></el-input>
      </el-form-item>
      <el-form-item label="所在宿舍">
        <el-input v-model="studentForm.studentDormitory"></el-input>
      </el-form-item>
      <el-form-item label="辅导员姓名">
        <el-input v-model="studentForm.studentCounsellor"></el-input>
      </el-form-item>
      <el-form-item label="辅导员电话" prop="counsellorTel">
        <el-input v-model="studentForm.counsellorTel"></el-input>
      </el-form-item>
      <el-form-item label="个人信息" prop="content">
        <div class="editor">
          <quill-editor
            ref="editorRef"
            v-model:content="studentForm.studentInstruction"
            content-type="html"
            theme="snow"
          ></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
        <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
